<template>
  <div class="create-or-edit-book">
    <el-card>
      <!-- 头部标题 -->
      <div slot="header" class="clearfix">
        <el-pageHeader
          @back="goBack"
          :content="status === 'create' ? '添加书籍' : '编辑书籍'"
        ></el-pageHeader>
      </div>
      <!-- 底部表单 -->
      <el-form
        :model="book"
        label-position="left"
        label-width="70px"
        ref="form"
        :rules="rules"
        v-loading="isUploading"
      >
        <el-form-item
          label="书名"
          prop="bookName"
        >
          <el-input v-model="book.bookName"></el-input>
        </el-form-item>
        <el-form-item
          label="作者"
          prop="author"
        >
          <el-input v-model="book.author"></el-input>
        </el-form-item>
        <el-form-item
          label="出版社"
          prop="publisher"
        >
          <el-input v-model="book.publisher"></el-input>
        </el-form-item>
        <el-form-item
          label="页数"
          prop="pages"
        >
          <el-input-number
            v-model="book.pages"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="类别"
          prop="type"
        >
          <el-select
            v-model="book.type"
            placeholder="书籍类别"
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="总量"
          prop="amount"
        >
          <el-input-number
            v-model="book.amount"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="库存"
          prop="remain"
        >
          <el-input-number
            v-model="book.remain"
            :min="0"
            :max="book.amount"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          v-if="status === 'edit'"
          label="书评"
        >
          <el-button @click.native="handleCheckComments">点击查看</el-button>
        </el-form-item>
        <el-form-item
          label="封面"
          prop="coverUrl"
        >
          <!-- 上传区域 -->
          <el-upload
            v-if="!isCoverUploading"
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :http-request="handleCoverUpload"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: auto; height: 178px;">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- 加载区域 -->
          <el-progress
            v-else
            type="circle"
            :percentage="progress.percentage"
            :color="progress.color"
            :status="progress.status"
          ></el-progress>
        </el-form-item>
        <el-form-item
          label="简介"
          prop="description"
        >
          <el-input
            v-model="book.description"
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click.native="handleReset">重置表单</el-button>
          <el-button
            v-if="status === 'edit'"
            @click.native="handleOwners"
          >查看持有者</el-button>
          <el-button
            v-if="status === 'create'"
            @click.native="handleAdd"
            type="primary"
          >添加书籍</el-button>
          <el-button
            v-else
            @click.native="handleEdit"
            type="primary"
          >修改书籍</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 编辑时显示持有者 -->
    <el-dialog :visible.sync="isCheckOwners">
      <el-card>
        <div slot="header" class="clearfix main-title">《{{ book.bookName }}》持有者</div>
        <el-table
          :data="owners"
          stripe
        >
          <el-table-column
            prop="_id"
            label="学号"
          ></el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
          ></el-table-column>
          <el-table-column
            prop="status"
            label="状态"
          >
            <template slot-scope="scope">
              <el-tag
              v-if="scope.row.status"
              type="success"
            >正常</el-tag>
            <el-tag
              v-else
              type="danger"
            >超时</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                type="danger"
                @click.native="handleGiveBack(scope)"
              >强制归还</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-dialog>
    <!-- 编辑时查看所有书评 -->
    <el-dialog :visible.sync="isCheckComments">
      <el-card>
        <div slot="header" class="clearfix main-title">《{{ book.bookName }}》书评</div>
        <el-table
          :data="book.comments"
          stripe
        >
          <el-table-column
            prop="commentId"
            label="评论编号"
          ></el-table-column>
          <el-table-column
            prop="content"
            label="内容"
          ></el-table-column>
          <el-table-column
            label="操作"
          >
            <template slot-scope="scope">
              <el-button @click="handleInspest(scope)">编辑</el-button>
              <el-button
                type="danger"
                @click="handleDelete(scope)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-dialog>
    <!-- 编辑时检视某条书评 -->
    <el-dialog
      :visible.sync="isInspect"
      :before-close="handleCancel"
    >
      <el-form
        ref="commentForm"
        :model="commentForm"
      >
        <el-form-item label="评论内容">
          <el-input type="textarea" v-model="commentForm.content"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click.native="handleCancel">取消</el-button>
          <el-button @click.native="handleCommentUpdate" type="primary">修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addBook, getTypeList, uploadImage, getBook, giveBackBook, editBook } from '@/services/book'
import { getEditUser } from '@/services/user'
import { editBookComment, deleteBookComment } from '@/services/comment'
export default {
  name: 'CreateOrEditBook',
  props: {
    status: {
      type: String,
      default: 'create'
    },
    bookId: {
      type: [Number, String]
    }
  },
  data () {
    return {
      // 书籍信息
      book: {
        bookName: '',
        coverUrl: '',
        description: '',
        author: '',
        pages: 0,
        comments: [],
        amount: 0,
        remain: 0,
        status: true,
        groupId: '',
        type: '',
        publisher: '',
        owners: []
      },
      // 表格类别内容
      typeList: [],
      // 表单校验规则
      rules: {
        bookName: [
          { required: true, message: '书名不能为空', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '作者不能为空', trigger: 'blur' }
        ],
        publisher: [
          { required: true, message: '出版社不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类别不能为空', trigger: 'blur' }
        ],
        coverUrl: [
          { required: true, message: '封面不能为空', trigger: 'blur' }
        ]
      },
      // 图片的地址
      imageUrl: '',
      // 控制书籍所属者界面显示
      isCheckOwners: false,
      // 控制全部书评查看
      isCheckComments: false,
      // 控制某书评检视
      isInspect: false,
      // 书评内容表单
      commentForm: {
        commentId: null,
        content: ''
      },
      // 控制表单是否正在提交
      isUploading: false,
      // 封面是否正在提交
      isCoverUploading: false,
      // 进度条数据
      progress: {
        color: '#FFAAEE',
        status: null,
        percentage: 0
      },
      // 标记当前选中书评索引
      curComment: null,
      // 标记当前选中持有者索引
      curOwner: null,
      // 当前书本持有者信息
      owners: [],
      // 编辑前评论内容
      commentContentBeforeEdit: ''
    }
  },
  created () {
    if (this.status === 'edit') {
      this.loadBook()
    }
    this.loadTypeList()
  },
  methods: {
    // 加载编辑书本
    async loadBook () {
      const { data } = await getBook({
        bookId: this.bookId
      })
      if (data.errcode === 0) {
        this.book = JSON.parse(data.data[0])
        this.imageUrl = this.book.coverUrl
        // 再根据持有者id获取其信息
        const taskStack = []
        this.book.owners.forEach(item => {
          taskStack.push(getEditUser({
            _id: item
          }))
        })
        const ownerResults = await Promise.all(taskStack)
        ownerResults.forEach(item => {
          this.owners.push(JSON.parse(item.data.data))
        })
      } else {
        this.$message.error('书籍类型信息获取失败，请联系开发者')
      }
    },
    // 加载书类
    async loadTypeList () {
      const { data } = await getTypeList()
      if (data.errcode === 0) {
        data.data.forEach(item => {
          const type = JSON.parse(item)
          this.typeList.push({
            label: type.label,
            value: type.typeId
          })
        })
      } else {
        this.$message.error('书籍类型信息获取失败，请联系开发者')
      }
    },
    // 后退操作
    goBack () {
      this.$router.back()
    },
    // 封面上传功能
    handleCoverUpload (option) {
      this.isCoverUploading = true
      const reader = new FileReader()
      reader.readAsDataURL(option.file)
      reader.onloadend = async () => {
        this.imageUrl = reader.result
        this.progress.status = null
        const imageData = {
          file: this.imageUrl
        }
        const { data } = await uploadImage(imageData, (event) => {
          this.progress.percentage = parseInt((event.loaded / event.total) * 100)
        })
        if (data.errcode === 0) {
          this.book.coverUrl = data.file_list[0].download_url
          this.progress.percentage = 0
          this.progress.status = 'success'
        } else {
          this.$message.error('上传封面失败，请联系开发者')
        }
        this.isCoverUploading = false
      }
    },
    // 封面上传前校验
    beforeCoverUpload (file) {
      const typeReg = /image\/*/
      const isImg = typeReg.test(file.type)
      const isLt4M = file.size / 1024 / 1024 < 4

      if (!isImg) {
        this.$message.error('上传头像只能是图片格式!')
      }
      if (!isLt4M) {
        this.$message.error('上传头像图片大小不能超过 4MB!')
      }
      return isImg && isLt4M
    },
    // 查看所属者
    handleOwners () {
      this.isCheckOwners = true
    },
    // 添加书籍
    handleAdd () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          this.$message.error('数据输入有误，请重新确认')
        } else {
          this.isUploading = true
          // 控制能否借出状态
          if (this.book.amount === 0 || this.book.remain === 0) {
            this.book.status = false
          }
          const { data } = await addBook(this.book)
          if (data.errcode === 0) {
            this.isUploading = false
            this.$message.success('添加成功')
            this.$router.push({
              name: 'book'
            })
          } else {
            this.$message.error('添加失败，请联系开发者')
          }
          this.isUploading = false
        }
      })
    },
    // 查看全部评论
    handleCheckComments () {
      this.isCheckComments = true
    },
    // 查看评论内容
    handleInspest (rowData) {
      this.isInspect = true
      this.curComment = rowData.$index
      this.commentForm = this.book.comments[this.curComment]
      this.commentContentBeforeEdit = this.book.comments[this.curComment].content
    },
    // 修改评论
    async handleCommentUpdate () {
      const { data } = await editBookComment({
        bookId: this.bookId,
        index: this.curComment,
        comment: this.commentForm
      })
      if (data.errcode === 0) {
        this.isInspect = false
        this.$message.success('修改成功')
      } else {
        this.$message.error('修改失败，请联系开发者')
      }
    },
    // 取消编辑评论
    handleCancel () {
      this.isInspect = false
      this.book.comments[this.curComment].content = this.commentContentBeforeEdit
    },
    // 删除评论
    handleDelete (rowData) {
      this.$confirm('确定删除评论吗？数据无法恢复！', '警告')
        .then(async res => {
          const { data } = await deleteBookComment({
            bookId: this.bookId,
            index: rowData.$index,
            commentId: this.book.comments[rowData.$index].commentId
          })
          if (data.errcode === 0) {
            this.book.comments.splice(rowData.$index, 1)
            this.$message.success('删除成功')
          } else {
            this.$message.error('删除失败，请联系开发者')
          }
        })
        .catch(() => {
          this.$message.info('删除取消')
        })
    },
    // 重置表单
    handleReset () {
      if (this.status === 'edit') {
        this.loadBook()
      } else {
        this.$refs.form.resetFields()
      }
    },
    // 强制归还
    handleGiveBack (rowData) {
      this.$confirm('确认强制归还吗？确认后无法控制借阅！', '警告')
        .then(async res => {
          this.curOwner = rowData.$index
          const { data } = await giveBackBook({
            bookId: this.bookId,
            index: rowData.$index
          })
          if (data.errcode === 0) {
            this.book.owners.splice(this.curOwner, 1)
            this.owners.splice(this.curOwner, 1)
            this.$message.success('成功归还！')
            this.book.remain++
          } else {
            this.$message.error('归还失败！请联系开发者')
          }
        })
        .catch(() => {
          this.$message.info('取消操作')
        })
    },
    // 提交编辑书籍
    async handleEdit () {
      if (this.book.amount === 0 || this.book.remain === 0) {
        this.book.status = false
      } else {
        this.book.status = true
      }
      const { data } = await editBook(this.book)
      if (data.errcode === 0) {
        this.$message.success('修改成功！')
        this.$router.push({
          name: 'book'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('~@/styles/my-form.scss');
@import url('~@/styles/my-button.scss');
@import url('~@/styles/my-checkbox.scss');
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #FF88FF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  ::v-deep .el-progress-circle {
    width: 178px !important;
    height: 178px !important;
  }
</style>
